package edu.hrbu.spring.controller;

import edu.hrbu.spring.common.R;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author 徐登宇
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @RequestMapping("download")
    public ResponseEntity download2() {
        try {
            String fileName = "1.jpg";
            byte[] bytes = FileUtils.readFileToByteArray(new File("D:/javaweb/springmvc/"+fileName));
            HttpHeaders headers=new HttpHeaders();
            // Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名。
            headers.set("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            headers.set("charsetEncoding","utf-8");
            headers.set("content-type","multipart/form-data");
            return new ResponseEntity<>(bytes,headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("/upload")
    public R upload(@RequestParam("file") CommonsMultipartFile file) {
        String uploadFileName = file.getOriginalFilename();
        String path="D:/javaweb/springmvc/upload";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        try {
            file.transferTo(new File(path + "/" + uploadFileName));
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }
        return R.success();
    }

}
